package com.yundasys.lab10designpattern.strategy;

import com.yundasys.lab10designpattern.strategy.enums.CouponTypeEnum;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author jiangta
 * @version 1.0
 * @date 2021/5/19 10:55 上午
 */
//@Component
//public class CouponDiscountFactory implements InitializingBean {
//
//    private Map<CouponTypeEnum, ICouponDiscount> couponMap = new ConcurrentHashMap<>();
//
//    @Override
//    public void afterPropertiesSet() throws Exception {
//        couponMap.put(CouponTypeEnum.MJ, new MJCouponDiscount());
//        couponMap.put(CouponTypeEnum.ZJ, new ZJCouponDiscount());
//        couponMap.put(CouponTypeEnum.ZK, new ZKCouponDiscount());
//        couponMap.put(CouponTypeEnum.NYG, new NYGCouponDiscount());
//    }
//
//    public ICouponDiscount route(CouponTypeEnum couponTypeEnum) {
//        ICouponDiscount iCouponDiscount = couponMap.get(couponTypeEnum);
//        return iCouponDiscount;
//    }
//}

@Component
public class CouponDiscountFactory {

    private Map<CouponTypeEnum, ICouponDiscount> couponMap = new ConcurrentHashMap<>();

    public CouponDiscountFactory(ObjectProvider<ICouponDiscount> provider) {
        couponMap = provider.orderedStream().collect(Collectors.toMap(ICouponDiscount::getCouponType, Function.identity(),(v1, v2) -> v2, ConcurrentHashMap::new));
    }

    public ICouponDiscount route(CouponTypeEnum couponTypeEnum) {
        ICouponDiscount iCouponDiscount = couponMap.get(couponTypeEnum);
        return iCouponDiscount;
    }
}
